package br.com.dev.tcc.util.alarm;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import br.com.dev.tcc.R;

public class AlarmUtil {

	private static long WEEK_REPEAT = 604800000;	
	
	private Context context;

	public AlarmUtil(Context context) {
		this.context = context;
	}

	public void createAlarm(int idApolice, Calendar startDate,
			String notificationText) {

		Intent intent = new Intent("br.com.dev.tcc.EXECUTE_ALARM");
		intent.putExtra("notificationText", notificationText);
		intent.putExtra("id", idApolice);
		intent.putExtra("titleText", context.getString(R.string.dia_licenca));

		PendingIntent it = PendingIntent.getBroadcast(context, idApolice,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);

		AlarmManager alarme = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);

		if (isMesmoDia(startDate, Calendar.getInstance())) {
			startDate = Calendar.getInstance();
		}

		long time = startDate.getTimeInMillis();

		alarme.set(AlarmManager.RTC_WAKEUP, time, it);
	}

	public void createAlarmRodizio(int idApolice, Calendar startDate,
			String notificationText) {

		Intent intent = new Intent("br.com.dev.tcc.EXECUTE_ALARM");

		intent.putExtra("notificationText", notificationText);
		intent.putExtra("id", idApolice);
		intent.putExtra("titleText", context.getString(R.string.dia_rodizio));

		PendingIntent it = PendingIntent.getBroadcast(context, idApolice,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);

		AlarmManager alarme = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);

		if (isMesmoDiaRodizio(startDate, Calendar.getInstance())) {
			startDate = Calendar.getInstance();
		}

		long time = startDate.getTimeInMillis();

		alarme.setRepeating(AlarmManager.RTC_WAKEUP, time, WEEK_REPEAT, it);
	}

	public void cancelAlarm(int idApolice) {

		PendingIntent it = PendingIntent.getBroadcast(context, idApolice,
				new Intent("br.com.dev.tcc.EXECUTE_ALARM"),
				PendingIntent.FLAG_UPDATE_CURRENT);

		AlarmManager alarme = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);

		alarme.cancel(it);
	}

	private boolean isMesmoDia(Calendar data1, Calendar data2) {

		return data1.get(Calendar.DAY_OF_YEAR) == data2
				.get(Calendar.DAY_OF_YEAR)
				&& data1.get(Calendar.YEAR) == data2.get(Calendar.YEAR);
	}

	private boolean isMesmoDiaRodizio(Calendar data1, Calendar data2) {

		return data1.get(Calendar.DAY_OF_WEEK) == data2
				.get(Calendar.DAY_OF_WEEK);
	}
}
